//
//  WZGSettingVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/5.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "WZGSettingVC.h"
#import "ZCSettingCell.h"
#import "ZCSettingFootView.h"
#import "ZCWebVC.h"
#import <GTSDK/GeTuiSdk.h>


extern NSString *baseURLStr;

@interface WZGSettingVC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, copy) NSArray<NSArray<NSMutableDictionary *> *> *datasource;

@end

@implementation WZGSettingVC

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  self.navigationController.navigationBarHidden = NO;
}

- (void)setupUI {
  self.navigationItem.title = @"系统设置";
  self.tableView.dataSource = self;
  self.tableView.delegate = self;
  
  [self.tableView registerNib:[UINib nibWithNibName:@"ZCSettingCell" bundle:nil]
       forCellReuseIdentifier:@"ZCSettingCell"];
  
  UIView *footerView = [[UIView alloc] initWithFrame:(CGRect){0,0,ScreenWidth,65}];
  UINib *nib = [UINib nibWithNibName:@"ZCSettingFootView" bundle:nil];
  ZCSettingFootView *view = [nib instantiateWithOwner:self options:nil].firstObject;
  view.frame = footerView.bounds;
  [view.btn addTarget:self
               action:@selector(exitBtnClickAction)
     forControlEvents:UIControlEventTouchUpInside];
  [footerView addSubview:view];
  self.tableView.tableFooterView = footerView;
  self.view.backgroundColor= [generalToolBox getColorWithHexadecimalColorStr:@"0xededed"];
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  NSArray *arr = self.datasource[section];
  return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSInteger section = indexPath.section;
  NSInteger row = indexPath.row;
  NSArray *arr = self.datasource[section];
  ZCSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCSettingCell"
                                                        forIndexPath:indexPath];
  cell.accessoryType = UITableViewCellAccessoryNone;
  if (section == 1) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  }
  cell.dict = arr[row];
  return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  return 65.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  if (section == 0) {
    return 0.001f;
  } else {
    return 15.0f;
  }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return 0.001;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  NSInteger section = indexPath.section;
  NSInteger row = indexPath.row;
  if (section == 0 ) {
    if ([[self getCacheSize] floatValue]<=0) {
      return;
    }
    [self clearCache];
    [tableView reloadData];
    [self.view makeToast:@"清理成功" duration:1 position:CSToastPositionCenter];
  }
  if (section == 1) {
    switch (row) {
      case 0://意见反馈
      {
      }
        break;
      case 1://版本说明
      {
        ZCWebVC *vc = [[ZCWebVC alloc] init];
        vc.navTitle = @"版本说明";
        NSString *path = [[NSBundle mainBundle] pathForResource:@"setting" ofType:@"bundle"];
        NSBundle *bundle = [NSBundle bundleWithPath:path];
        vc.localPath = [bundle pathForResource:@"version" ofType:@"html"];
        [self.navigationController pushViewController:vc animated:YES];
      }
        break;
      case 2://平台资质
      {
        ZCWebVC *vc = [[ZCWebVC alloc] init];
        vc.navTitle = @"平台资质";
        extern NSString *baseURLStr;
        NSString *url = [NSString stringWithFormat:@"%@%@",baseURLStr,@"/h5/index.html#/aptitude?from=app"];
        vc.remotePath = url;
        [self.navigationController pushViewController:vc animated:YES];
        
      }
        break;
      case 3://用户协议
      {
        ZCWebVC *vc = [[ZCWebVC alloc] init];
        vc.navTitle = @"用户协议";
        NSString *url = [NSString stringWithFormat:@"%@%@",baseURLStr,@"/h5/index.html#/rule1"];
        vc.remotePath = url;
        [self.navigationController pushViewController:vc animated:YES];
      }
        break;
      case 4://隐私协议
      {
        ZCWebVC *vc = [[ZCWebVC alloc] init];
        vc.navTitle = @"隐私协议";
        NSString *url = [NSString stringWithFormat:@"%@%@",baseURLStr,@"/h5/index.html#/rule2"];
        vc.remotePath = url;
        [self.navigationController pushViewController:vc animated:YES];
      }
        break;
        
      default:
      {}
        break;
    }
  }
  
}

// MARK: - GET

- (NSArray<NSArray<NSMutableDictionary *> *> *)datasource {
  NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
  _datasource = @[@[@{@"main":@"清除缓存",@"sub":[self getCacheSize]}],
                  @[@{@"main":@"意见反馈",@"sub":@""},
                    @{@"main":@"版本说明",@"sub":[infoDict valueForKey:@"CFBundleShortVersionString"]},
                    @{@"main":@"平台资质",@"sub":@""},
                    @{@"main":@"用户协议",@"sub":@""},
                    @{@"main":@"隐私协议",@"sub":@""},
                  ]];
  return _datasource;
}

// MARK: - Action

- (void)exitBtnClickAction {
  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  ZCBaseUserManager *manager = [ZCBaseUserManager shareInstance];
  manager.userModel = nil;
//  [GeTuiSdk unbindAlias:self.userModel.member.idstr andSequenceNum:self.userModel.member.idstr andIsSelf:YES];
//  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//
//  [ud setValue:nil forKey:@"userinfo"];
//  [ud setValue:nil forKey:@"upassTF"];
//  [ud setValue:nil forKey:@"accessToken"];
//
//  [ud removeObjectForKey:@"userinfo"];
//  [ud removeObjectForKey:@"upassTF"];
//  [ud removeObjectForKey:@"accessToken"];
//  [ud synchronize];
//
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"homereload" object:nil];
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"catereload" object:nil];
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"mainshoppingnum" object:@(0)];
//  [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
  [BaseViewModel sendMsg2RNWithCmd:BaseViewModelCmd_ResetUserInfo bridge:self.bridge params:@{}];
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [self.tabBarController setSelectedIndex:0];
    [self.navigationController popViewControllerAnimated:YES];
  });
}

- (NSString *)getCacheSize{
  //获取缓存图片的大小(字节)
  //    NSUInteger bytesCache = [[SDImageCache sharedImageCache] getSize];
  //换算成 MB (注意iOS中的字节之间的换算是1000不是1024)
  //    float MBCache = bytesCache/1000/1000;
  
  double MBCache = [self cacheSize]/1000/1000;
  
  return [NSString stringWithFormat:@"%.2lfMB",MBCache];
}


/*
 自定义方法：获取缓存大小
 */
- (double)cacheSize{
  //获取文件管理器
  NSFileManager *fileM = [NSFileManager defaultManager];
  //获取缓存路径
  NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  
  //得到缓存文件列表
  NSArray *childPaths = [fileM subpathsAtPath:cachePath];
  
  //存储文件总长度
  double size = 0;
  for(NSString *childPath in childPaths){
    //得到文件路径
    NSString *filePath = [cachePath stringByAppendingPathComponent:childPath];
    
    //获取当前是文件还是目录
    BOOL isDir = NO;
    [fileM fileExistsAtPath:filePath isDirectory:&isDir];
    
    if(isDir){//如果是目录则跳出此次循环
      continue;
    }
    
    //将文件大小累加
    size = size + [[fileM attributesOfItemAtPath:filePath error:nil][NSFileSize] doubleValue];
  }
  return size;
}

- (void)clearCache{
  //获取文件管理器
  NSFileManager *fileM = [NSFileManager defaultManager];
  //获取缓存路径
  NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  //清除缓存
  [fileM removeItemAtPath:cachePath error:nil];
}
@end
